package com.socket.learing.udp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by 张波 on 2019/12/10.
 */
@Slf4j
public class SendService {

    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();

        byte[] bytes = "发送消息".getBytes();
        DatagramPacket request = new DatagramPacket(bytes, bytes.length);
//        request.setAddress(Inet4Address.getLocalHost());
        request.setAddress(InetAddress.getByName("255.255.255.255"));
        request.setPort(20000);
        datagramSocket.send(request);
        System.out.println("发送结束");

        byte[] buf = new byte[512];
        DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length);
        datagramSocket.receive(datagramPacket);

        String msg = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
        log.info("接收到信息，IP：{},port:{},data:{}", datagramPacket.getAddress().getHostAddress(),
                datagramPacket.getPort(), msg);

        datagramSocket.close();
    }
}
